//
//  GoodsDetailVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2018/1/9.
//  Copyright © 2018年 LJL. All rights reserved.
//

#import "GoodsDetailVC.h"
#import "TLChatViewController.h"
#import "GoodsDetailCell.h"
#import "GoodsArtCell.h"
#import "QueRenViewController.h"
#import "GoodsDetailApi.h"
#import "XiangQingViewController.h"
#import "IGGoodsAddOrderApi.h"
#import "PYClubPresentDetailImgTableViewCell.h"
@interface GoodsDetailVC ()<UITableViewDelegate, UITableViewDataSource>
{
    UIView *bottomView;
    UIView *contactBtn;
    UIButton *buyBtn;
    NSString *str1;
}
@property (strong, nonatomic) UITableView *table;
@property (strong, nonatomic) NSArray *imageArr;
@property (nonatomic, strong) GoodsDetailApi *api;
@property (nonatomic, strong) GoodsDetailModel *model;
@end

@implementation GoodsDetailVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"商品详情";
    [self ctreatTableView];
    [self loadData];
}
 
- (void)ctreatTableView
{
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KSCREENWIDTH, KSCREENHEIGHT - 64 - 44) style:UITableViewStylePlain];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>= 11.0)
    {
        self.table.estimatedRowHeight = 0;
        self.table.estimatedSectionHeaderHeight = 0;
        self.table.estimatedSectionFooterHeight = 0;
    }
    self.table.backgroundColor = [UIColor c2Color];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.table registerClass:[PYClubPresentDetailImgTableViewCell class] forCellReuseIdentifier:@"PYClubPresentDetailImgTableViewCell"];
    [self.table registerNib:[UINib nibWithNibName:@"GoodsDetailCell" bundle:nil] forCellReuseIdentifier:@"GoodsDetailCell"];
    [self.table registerNib:[UINib nibWithNibName:@"GoodsArtCell" bundle:nil] forCellReuseIdentifier:@"GoodsArtCell"];
    [self.view addSubview:_table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-44);
        make.top.mas_equalTo(0);
    }];
//    @KWeakObj(self)
//    [self.table ig_setHeaderWithRefreshingBlock:^{
//        [selfWeak loadData];
//
//        selfWeak.page = 1;
//        selfWeak.lastTimeDate = @"";
//        [selfWeak loadComment];
//    }];

    
    
    bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor c3Color];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    contactBtn = [[UIView alloc] init];
    contactBtn.userInteractionEnabled = YES;
    contactBtn.backgroundColor = [UIColor c3Color];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contactBtnClick)];
    [contactBtn addGestureRecognizer:tap];
    [bottomView addSubview:contactBtn];
    [contactBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(100);
    }];
    
    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me-mail"]];
    imageV.backgroundColor = [UIColor clearColor];
    imageV.frame = CGRectMake(37, 5, 26, 20);
    [contactBtn addSubview:imageV];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, 100, 15)];
    label.text = @"联系卖家";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor c4Color];
    label.font = [UIFont systemFontOfSize:13];
    [contactBtn addSubview:label];
    
    buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    buyBtn.backgroundColor = [UIColor appColor];
    [buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buyBtn addTarget:self action:@selector(buyBtnclick) forControlEvents:UIControlEventTouchUpInside];
    buyBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:buyBtn];
    [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(0);
        make.left.mas_equalTo(100);
    }];

}

- (void)loadData
{
    self.api = [GoodsDetailApi new];
    self.model = [GoodsDetailModel new];
    self.api.goodsId = _goodsId;
    __weak typeof(self) weakSelf = self;
    [self.api startWithDecodeClass:[GoodsDetailResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            GoodsDetailResp *resp = responseObject;
            weakSelf.model = resp.data;
            [weakSelf.table reloadData];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _model.title ? 4 : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    CGFloat x = cell.separatorInset.left;
//    UIFont *font = [UIFont systemFontOfSize:14];
//    CGFloat h = [self tableView:tableView heightForRowAtIndexPath:indexPath];
//    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0)
    {
        cell.backgroundColor = [UIColor c2Color];
        UIImageView *imageV = [[UIImageView alloc] init];
        [imageV sd_setImageWithURL:[NSURL URLWithString:_model.mainImage]];
        imageV.contentMode = UIViewContentModeScaleAspectFill;
        imageV.layer.masksToBounds = YES;
        imageV.backgroundColor = [UIColor clearColor];
        [cell addSubview:imageV];
        [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.left.right.mas_equalTo(0);
            make.center.mas_equalTo(cell.center);
//            make.left.right.top.bottom.mas_equalTo(0);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = _model.auditReason ? [NSString stringWithFormat:@"审核未通过原因: %@", _model.auditReason]: @"";
        label.textColor = [UIColor c3Color];
        label.backgroundColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:15];
        label.alpha = 0.6;
        label.hidden = [_model.status isEqualToString:@"3"] ? NO : YES;
        [cell addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_equalTo(0);
            make.height.mas_equalTo(40);
        }];
        return cell;
    }
    else if (indexPath.section == 1)
    {
        GoodsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsDetailCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(_model.author && ![_model.author isEqualToString:@""])
        {
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ | %@", _model.title, _model.author]];
            NSRange titleRange = NSMakeRange(0, [[str string] rangeOfString:@"|"].location - 2);
            NSRange nameRange = NSMakeRange([[str string] rangeOfString:@"|"].location, [str string].length - titleRange.length - 2);
            [str addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18], NSFontAttributeName, [UIColor c4Color],NSForegroundColorAttributeName, nil] range:titleRange];
            [str addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, [UIColor c5Color],NSForegroundColorAttributeName, nil] range:nameRange];
            cell.titleL.attributedText = str;
        }
        else
        {
           cell.titleL.text = _model.title;
        }
        cell.nameL.text = _model.seller;
        cell.priceL.text = [NSString stringWithFormat:@"¥%@", _model.price];
        cell.inventoryL.text = [NSString stringWithFormat:@"库存%@", _model.stock];
        
        NSString *classChildStr, *sizeStr, *yearStr;
        if(_model.gclassChild && ![_model.gclassChild isEqualToString:@""])
        {
            classChildStr = [NSString stringWithFormat:@"| %@ ",_model.gclassChild];
        }else{
            classChildStr = @"";
        }
        if(_model.size && ![_model.size isEqualToString:@""])
        {
            sizeStr = [NSString stringWithFormat:@"| %@ ",_model.size];
        }else{
            sizeStr = @"";
        }
        if(_model.years && ![_model.years isEqualToString:@""])
        {
            yearStr = [NSString stringWithFormat:@"| %@ ",_model.years];
        }else{
            yearStr = @"";
        }
        cell.detailL.text = [NSString stringWithFormat:@"%@ %@%@%@", _model.gclass, classChildStr, sizeStr, yearStr];
        return cell;
    }
    else if (indexPath.section == 2)
    {
        GoodsArtCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsArtCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:_model.worksImage]];
        cell.titleL.text = _model.worksTitle;
        return cell;
    }
    else if (indexPath.section == 3)
    {
        if (indexPath.row == 0)
        {
            cell.backgroundColor = [UIColor c2Color];
            UILabel *label = [[UILabel alloc] init];
            label.textColor = [UIColor c4Color];
            label.numberOfLines = 0;
            label.text = _model.content;
            label.font = [UIFont systemFontOfSize:15];
            label.backgroundColor = [UIColor clearColor];
            [cell addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-10);
                make.left.top.mas_equalTo(10);
                make.bottom.mas_equalTo(0);
            }];
            return cell;
        }
        else if (indexPath.row == (_model.otherImages.count + 1))
        {
            cell.backgroundColor = [UIColor c2Color];
            UILabel *label = [[UILabel alloc] init];
            label.textColor = [UIColor c5Color];
            label.text = [_model.allowRefund isEqualToString:@"1"] ? @"该商品支持退换货" : @"该商品不支持退换货";
            label.font = [UIFont systemFontOfSize:13];
            label.backgroundColor = [UIColor clearColor];
            [cell addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-10);
                make.left.top.mas_equalTo(10);
                make.bottom.mas_equalTo(-15);
            }];
            return cell;
        }
        else
        {
            PYClubPresentDetailImgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PYClubPresentDetailImgTableViewCell"];
            if (nil == cell) {
                cell = [[PYClubPresentDetailImgTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PYClubPresentDetailImgTableViewCell"];
            }
            [self configureCell:cell atIndexPath:indexPath];
            cell.userInteractionEnabled = NO;
            return cell;
        }
    }
    return cell;
}

- (void)configureCell:(PYClubPresentDetailImgTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSString *imgURL = _model.otherImages[indexPath.row - 1];
    UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgURL];
    
    if ( !cachedImage ) {
        [self downloadImage:imgURL forIndexPath:indexPath];
        [cell.btn setBackgroundImage:[UIImage imageNamed:@"背景_首次登录"] forState:UIControlStateNormal];
    } else {
        [cell.btn setBackgroundImage:cachedImage forState:UIControlStateNormal];
    }
}

- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath {
    // 利用 SDWebImage 框架提供的功能下载图片
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES completion:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.table reloadData];
            });
        }];
    }];
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2)
    {
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.isRoot = YES;
        vc.p_id = _model.worksId;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        return 1;
    }
    else if (section==1)
    {
        return 1;
    }
    else if (section==2)
    {
        if ([_model.ifProduct isEqualToString:@"1"])
        {
            return 1;
        }
        return 0;
    }
    else if (section==3)
    {
        return _model.otherImages.count + 2;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return 363 * (KSCREENWIDTH / 375);
    }
    else if (indexPath.section==1)
    {
        return 130;
    }
    else if (indexPath.section==2)
    {
        return 83;
    }
    else if (indexPath.section==3)
    {
        if (indexPath.row == 0)
        {
            if (_model.content && ![_model.content isEqualToString:@""])
            {
                NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
                CGSize size = [_model.content boundingRectWithSize:CGSizeMake(KSCREENWIDTH-20, 0) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
                return size.height+15;
            }
            return 0;
        }
        else if (indexPath.row == (_model.otherImages.count + 1))
        {
            return 40;
        }
        else
        {
            // 先从缓存中查找图片
            UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey: _model.otherImages[indexPath.row - 1]];
            // 没有找到已下载的图片就使用默认的占位图，当然高度也是默认的高度了，除了高度不固定的文字部分。
            if (!image) {
                image = [UIImage imageNamed:@"背景_首次登录"];
            }
            //手动计算cell
            CGFloat imgHeight =  (KSCREENWIDTH - 20) * image.size.height / image.size.width;
            return imgHeight;
        }
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==2)
    {
        return .5f;
    }
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .01f;
}

- (void)contactBtnClick
{
    if ([_model.sellerId isEqualToString:[IGUser getUid]])
    {
        [self presentMessageTips:@"您不能给自己发私信"];
        return;
    }
    
#warning by zqs  防闪退
    if (_model.sellerId == nil) {
        return;
    }
    
    TLChatViewController *vc = [TLChatViewController new];
    vc.otherId = _model.sellerId;
    vc.navigationItem.title = _model.seller;
    [UIViewController ig_pushViewController:vc animated:YES];
}

- (void)buyBtnclick
{
    if ([_model.sellerId isEqualToString:[IGUser getUid]])
    {
        [self presentMessageTips:@"您不能购买自己的商品"];
        return;
    }
    if (![_model.status isEqualToString:@"2"])
    {
        [self presentMessageTips:@"当前商品无法购买"];
        return;
    }
    if ([_model.status isEqualToString:@"2"])
    {
        IGGoodsAddOrderApi *orderApi = [IGGoodsAddOrderApi new];
        orderApi.goodsId = _model.goodsId;
        [orderApi startWithDecodeClass:[IGGoodsAddOrderResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject)
            {
                IGGoodsAddOrderResp * resp = responseObject;
                IGGoodsAddOrderModel *model = resp.data;
                if ([model.method isEqualToString:@"toOrder"])
                {
                    QueRenViewController * vc = [[QueRenViewController alloc] init];
                    vc.model = model;
                    vc.type = 1;
                    [UIViewController ig_pushViewController:vc animated:YES];
                }
            }
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



@end
